using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using RestaurantFinder.Core.Models;
using RestaurantFinder.Core.Services;
using System.Text.Json;

namespace RestaurantFinder.Infrastructure.Services;

/// <summary>
/// 基于浏览器SessionStorage的页面状态管理服务
/// </summary>
public class BrowserPageStateService : IPageStateService
{
    private readonly IJSRuntime _jsRuntime;
    private readonly ILogger<BrowserPageStateService> _logger;
    private const string RESTAURANT_DISCOVERY_KEY = "restaurant_discovery_state";

    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        WriteIndented = false
    };

    public BrowserPageStateService(IJSRuntime jsRuntime, ILogger<BrowserPageStateService> logger)
    {
        _jsRuntime = jsRuntime;
        _logger = logger;
    }

    /// <summary>
    /// 保存餐厅发现页面状态到SessionStorage
    /// </summary>
    public async Task SaveRestaurantDiscoveryStateAsync(RestaurantDiscoveryState state)
    {
        try
        {
            state.SavedAt = DateTime.Now;
            var json = JsonSerializer.Serialize(state, _jsonOptions);
            await _jsRuntime.InvokeVoidAsync("sessionStorage.setItem", RESTAURANT_DISCOVERY_KEY, json);
            
            _logger.LogInformation("💾 已保存餐厅发现页面状态：{Count} 家餐厅，选中：{Selected}", 
                state.Restaurants.Count, state.SelectedRestaurant?.Name ?? "无");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "保存页面状态失败");
        }
    }

    /// <summary>
    /// 从SessionStorage获取餐厅发现页面状态
    /// </summary>
    public async Task<RestaurantDiscoveryState?> GetRestaurantDiscoveryStateAsync()
    {
        try
        {
            var json = await _jsRuntime.InvokeAsync<string?>("sessionStorage.getItem", RESTAURANT_DISCOVERY_KEY);
            
            if (string.IsNullOrEmpty(json))
            {
                _logger.LogDebug("💾 未找到保存的页面状态");
                return null;
            }

            var state = JsonSerializer.Deserialize<RestaurantDiscoveryState>(json, _jsonOptions);
            
            if (state?.IsValid == true)
            {
                _logger.LogInformation("🔄 恢复页面状态：{Count} 家餐厅，选中：{Selected}，保存于：{SavedAt}", 
                    state.Restaurants.Count, state.SelectedRestaurant?.Name ?? "无", state.SavedAt.ToString("HH:mm:ss"));
                return state;
            }
            else
            {
                _logger.LogInformation("⏰ 页面状态已过期，自动清除");
                await ClearRestaurantDiscoveryStateAsync();
                return null;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取页面状态失败");
            return null;
        }
    }

    /// <summary>
    /// 清除餐厅发现页面状态
    /// </summary>
    public async Task ClearRestaurantDiscoveryStateAsync()
    {
        try
        {
            await _jsRuntime.InvokeVoidAsync("sessionStorage.removeItem", RESTAURANT_DISCOVERY_KEY);
            _logger.LogInformation("🗑️ 已清除餐厅发现页面状态");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "清除页面状态失败");
        }
    }

    /// <summary>
    /// 检查是否存在保存的状态
    /// </summary>
    public async Task<bool> HasSavedStateAsync(string stateKey)
    {
        try
        {
            var json = await _jsRuntime.InvokeAsync<string?>("sessionStorage.getItem", stateKey);
            return !string.IsNullOrEmpty(json);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查状态存在性失败");
            return false;
        }
    }
} 